//
//  mttBackgroundImage.m
//  mtt
//
//  Created by Gerfried Mikusch on 10.08.10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "mttBackgroundImage.h"
#import "mttBgImgMenuViewController.h"

@implementation mttBackgroundImage

@synthesize longPressRecognizer, panRecognizer, rotationRecognizer, pinchRecognizer, menuPopover, delegate;


BOOL editMode;
mttBgImgMenuViewController *menuView;


#pragma mark -
#pragma mark hit testing

-(UIView *) hitTest:(CGPoint)point withEvent:(UIEvent *)event {
	
	//HitTest on non-Transparent pixels
	
	CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
	CGBitmapInfo info = kCGImageAlphaPremultipliedLast;
	
	UInt32 bitmapData[1];
	bitmapData[0] = 0;
	
	
	
	CGContextRef context = CGBitmapContextCreate(bitmapData, 1, 1, 8, 4, colorspace, info);
	CGRect rect = CGRectMake(-point.x, point.y - CGImageGetHeight(self.image.CGImage), CGImageGetWidth(self.image.CGImage), CGImageGetHeight(self.image.CGImage));
	
	CGContextDrawImage(context, rect, self.image.CGImage);
	CGContextFlush(context);
	
	if (bitmapData[0] != 0) {
		CGContextRelease(context);
		CGColorSpaceRelease(colorspace);
		return self;
	} else {
		return nil;
	}
	
}

#pragma mark -
#pragma mark point operations

-(void)setAnchorPointBetweenFirstLocation:(CGPoint)firstLocation andSecondLocation:(CGPoint)secondLocation {
	
	
	CGFloat minX;
	CGFloat maxX;
	CGFloat minY;
	CGFloat maxY;
	
	//Welcher der X bzw. Y Werte ist der kleine. Notwendig für die berechnung des Mittelpunkts
	if (firstLocation.x < secondLocation.x) {
		minX = firstLocation.x;
		maxX = secondLocation.x;
	} else {
		minX = secondLocation.x;
		maxX = firstLocation.x;
	}
	
	if (firstLocation.y < secondLocation.y) {
		minY = firstLocation.y;
		maxY = secondLocation.y;
	} else {
		minY = secondLocation.y;
		maxY = firstLocation.y;
	}
	
	//Berechne Mittelpunkt der beiden touches
	CGFloat newX = minX + (maxX-minX)/2;
	CGFloat newY = minY + (maxY-minY)/2;
	CGPoint newCenter = CGPointMake(newX, newY);
	//NSLog(@"newCenter x:%f, y:%f", newCenter.x, newCenter.y);
	
	
	//Den neuen Mittelpunkt in das Koordinatensystem der Superview konvertieren
	CGPoint newCenterConverted = [self convertPoint:newCenter toView:self.superview];
	//NSLog(@"convertedCenter x:%f, y:%f", newCenterConverted.x, newCenterConverted.y);
	
	//Den neuen Mittelpunkt normalisieren
	CGPoint normNewCenter = CGPointMake(newCenter.x/self.bounds.size.width, newCenter.y/self.bounds.size.height);
	//NSLog(@"normCenter x:%f, y:%f", normNewCenter.x, normNewCenter.y);
	
	//NSLog(@"oldLayerPosition x:%f, y:%f", self.layer.position.x, self.layer.position.y);
	
	
	//Ankerpunkt und neue Position setzen
	self.layer.anchorPoint = normNewCenter;
	
	//Position des Layers neu setzen, da die änderung des anchorpoints diese auch verändert, also wieder zurücksetzen
	self.layer.position = newCenterConverted;
	//NSLog(@"NewlayerPosition x:%f, y:%f", self.layer.position.x, self.layer.position.y);
	
}




#pragma mark -
#pragma mark gesture recognizing


-(void)handleLongPress:(UILongPressGestureRecognizer *)recognizer {
	
	if (recognizer.state == UIGestureRecognizerStateBegan) {
		
		CGPoint hitPoint = [recognizer locationInView:self];
		menuView = [[mttBgImgMenuViewController alloc] initWithNibName:@"mttBgImgMenuViewController" bundle:[NSBundle mainBundle]];
		menuView.delegate = self;
		menuView.editSwitch.on = editMode;
		menuPopover = [[UIPopoverController alloc] initWithContentViewController:menuView];
		[menuPopover setPopoverContentSize:menuView.view.frame.size animated:YES];
		[menuPopover presentPopoverFromRect:CGRectMake(hitPoint.x, hitPoint.y, 10, 10) inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		
	}
}


// Bewegt das Bild
-(void)handlePan:(UIPanGestureRecognizer *)recognizer {
		
	if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
		CGPoint translation = [recognizer translationInView:self.superview];
		[self setCenter:CGPointMake(self.center.x + translation.x, self.center.y + translation.y)];
		[recognizer setTranslation:CGPointZero inView:self.superview];
	}
	
}

// Rotiert das Bild
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer {
	
	//Ankerpunkt neu setzen
	if ([recognizer state] == UIGestureRecognizerStateBegan) {
		//NSLog(@"RotationBegan");
		//Position der Touches ermitteln
		CGPoint firstLocation = [recognizer locationOfTouch:0 inView:self];
		CGPoint secondLocation = [recognizer locationOfTouch:1 inView:self];
		//NSLog(@"fistTouch x:%f, y:%f", firstLocation.x, firstLocation.y);
		//NSLog(@"secondTouch x:%f, y:%f", secondLocation.x, secondLocation.y);
		
		//set new anchorpoint
		[self setAnchorPointBetweenFirstLocation:firstLocation andSecondLocation:secondLocation];
	}
	
	
    if ([recognizer state] == UIGestureRecognizerStateBegan || [recognizer state] == UIGestureRecognizerStateChanged) {
		self.transform = CGAffineTransformRotate(self.transform, [recognizer rotation]);
        [recognizer	setRotation:0];
    }
	
	if([recognizer state] == UIGestureRecognizerStateEnded) {
		
		CGPoint point = CGPointMake(self.bounds.size.width, self.bounds.size.height);
		
		[self setAnchorPointBetweenFirstLocation:self.bounds.origin andSecondLocation:point];		
	}
	
}

// Skaliert das Bild
- (void)handlePinch:(UIPinchGestureRecognizer *) recognizer {
	
	//Ankerpunkt neu setzen
	if ([recognizer state] == UIGestureRecognizerStateBegan) {
		//NSLog(@"RotationBegan");
		//Position der Touches ermitteln
		CGPoint firstLocation = [recognizer locationOfTouch:0 inView:self];
		CGPoint secondLocation = [recognizer locationOfTouch:1 inView:self];
		//NSLog(@"fistTouch x:%f, y:%f", firstLocation.x, firstLocation.y);
		//NSLog(@"secondTouch x:%f, y:%f", secondLocation.x, secondLocation.y);
		
		//set new anchorpoint
		[self setAnchorPointBetweenFirstLocation:firstLocation andSecondLocation:secondLocation];
	}
	
	
	if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
		self.transform = CGAffineTransformScale(self.transform, recognizer.scale, recognizer.scale);
		recognizer.scale = 1;
	}
	
	if([recognizer state] == UIGestureRecognizerStateEnded) {
		
		CGPoint point = CGPointMake(self.bounds.size.width, self.bounds.size.height);
		
		[self setAnchorPointBetweenFirstLocation:self.bounds.origin andSecondLocation:point];		
	}
}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    
	if (gestureRecognizer == self.pinchRecognizer ||
		gestureRecognizer == self.rotationRecognizer ||
		gestureRecognizer == self.panRecognizer ||
		otherGestureRecognizer == self.pinchRecognizer ||
		otherGestureRecognizer == self.rotationRecognizer ||
		otherGestureRecognizer == self.panRecognizer) {
		return YES;
	}
	return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    return YES;
}

-(void)setGestureRecognizersEnabled:(BOOL)enabled {
	
	//LongTap soll immer gehen
	self.pinchRecognizer.enabled = enabled;
	self.rotationRecognizer.enabled = enabled;
	self.panRecognizer.enabled = enabled;
	
}

#pragma mark -
#pragma mark mttBgImgMenuViewController Delegate Methods

-(void)didRemoveBackground {
	
	[self removeFromSuperview];
	[[self menuPopover] dismissPopoverAnimated:YES];
	
	//sollte der Hintergrund während des editieren gelöscht werden, müssen alle Bilder wieder aktiviert werden.
	if (panRecognizer.enabled) {
		[delegate setImagesAlpha:1.0];
		[delegate setImagesInteraction:YES];
	}
}

-(void)didSwitchEditMode:(UISwitch *) sender {
	
	if (sender.on) {
		[delegate setImagesAlpha:0.0];
		[delegate bringViewToFront:self];
		[delegate bringOptionViewToFront];
		
	} else {
		[delegate setImagesAlpha:1.0];
		[delegate sendViewToBack:self];
		[delegate sendViewToBack:[delegate getHelp]];
	}
	
	[delegate setImagesInteraction:!sender.on];
	[self setGestureRecognizersEnabled:sender.on];
	[[self menuPopover] dismissPopoverAnimated:YES];
	editMode = sender.on;
	
}

-(BOOL)isEditMode {
	return editMode;
}



#pragma mark -
#pragma mark init & dealloc

- (id)initWithImage:(UIImage *)image {
	[super initWithImage:image];
	
	
	self.contentMode = UIViewContentModeScaleAspectFill;
	CGRect rect = self.frame;
	rect.size = CGSizeMake(1024, 768);
	self.frame = rect;
	
	
	[self setUserInteractionEnabled:YES];
	[self setMultipleTouchEnabled:YES];
	
	
	UIGestureRecognizer *recognizer;
	
	recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
	[self addGestureRecognizer:recognizer];
	self.longPressRecognizer = (UILongPressGestureRecognizer *) recognizer;
	recognizer.delegate = self;
	[recognizer release];
	
	recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
	[self addGestureRecognizer:recognizer];
	self.panRecognizer = (UIPanGestureRecognizer *)recognizer;
	self.panRecognizer.maximumNumberOfTouches = 2;
	recognizer.delegate = self;
	[recognizer release];
	
	recognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
	[self addGestureRecognizer:recognizer];
	self.rotationRecognizer = (UIRotationGestureRecognizer *)recognizer;
	recognizer.delegate = self;
	[recognizer release];
	
	recognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
	[self addGestureRecognizer:recognizer];
	self.pinchRecognizer = (UIPinchGestureRecognizer *)recognizer;
	recognizer.delegate = self;
	[recognizer release];
	
	//Kurze Animation des hintergrunds um darauf aufmerksam zu machen!
	CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:nil context:context];
	[UIView setAnimationDuration:0.2];
	
	self.transform = CGAffineTransformMakeScale(1.1, 1.1);
	self.transform = CGAffineTransformMakeScale(1.0, 1.0);
    
    [UIView commitAnimations];
	
	[self setGestureRecognizersEnabled:NO];
	editMode = NO;
	
	return self;
}

- (void) dealloc {
	
	[longPressRecognizer release];
	[panRecognizer release];
	[rotationRecognizer release];
	[pinchRecognizer release];
	[menuPopover release];
	[super dealloc];
	
}


@end
